#include "../include/SockStream.h"
#include "../include/SockConnector.h"
#include <errno.h>

#include <time.h>
#include <iostream>
#include <string.h>

struct MsgHeader
{
    int msgid;
    int msglen;
};
int main (int argc, char *argv[])
{
    if (argc != 6)
    {
	std::cout << "usage : program 192.168.1.49 8889 4096 0(no heartbeat) 0(block)" << std::endl;
	return -1;
    }
    InetAddr remote_addr (atoi(argv[2]), argv[1]);
    int connect_num = atoi(argv[3]);
    if (connect_num <= 0) 
    {
	std::cout << "connect num is invalid\n" ;
	return -1;
    }
    SockStream *peer = new SockStream[connect_num];
    SockConnector connector;
    int i = 0;
    int count = 0;
    int timeout = atoi (argv[5]);
    TimeValue tv(timeout);
    while (i < connect_num)
    {
	if (connector.connect (peer[i++], remote_addr, 
		    timeout == 0 ? 0 : &tv) != 0)
	{
	    std::cout << "connect failed" << errno << "\n";
	    return -1;
	}
	count++;
    }
    std::cout << "connect success number = " << count << std::endl;
    int has_heartbeat = atoi(argv[4]);
    if (has_heartbeat)
    {
	char buff[512] = {0};
	MsgHeader msgh;
	msgh.msgid = 200;
	msgh.msglen = sizeof(buff);
	int times = 0;
	while (times++ < 1000)
	{
	    int n = 0;
	    struct iovec iov[2];
	    iov[0].iov_base = &msgh;
	    iov[0].iov_len  = sizeof(msgh);
	    iov[1].iov_base = buff;
	    iov[1].iov_len  = sizeof(buff);
	    while (n < connect_num)
	    {
		int send_bytes = 0;
		if ((send_bytes = peer[n].sendv (iov, 2)) <= 0)
		{
		    break;
		}
		n++;
	    }
	    //sleep (1);
	}
    }
    i = 0;
    while (i < connect_num)
    {
	peer[i++].close ();
    }
    return 0;
}
